<template>
  <div class="book-detail">
    <t-card :bordered="false" class="card">
      <template #title>
        <div class="card-title">小程序首页</div>
      </template>
      <template #actions>
        <t-button @click="goProductAdd" class="add-btn">
          <p class="flex align-center">
            <icon-font name="add" class="mr4"></icon-font>
            新增
          </p>
        </t-button>
      </template>

      <div class="content">
        <div class="classify">
          <t-tree :data="items" :actived="[params.pid]" activable :hover="false" transition expandParent expandOnClickNode @click="classifyClick">
            <template #label="{ node }">
              <p class="flex align-center justify-between">
                <span>{{ node.label }}</span>
                <t-dropdown v-if="node.value != 0" :min-column-width="80" trigger="hover">
                  <template #dropdown>
                    <t-dropdown-menu>
                      <t-dropdown-item>
                        <t-link class="edit-btn-color flex align-center justify-center" hover="color" theme="primary" @click="editClassify(node)">编辑</t-link>
                      </t-dropdown-item>
                      <t-dropdown-item >
                        <t-link class="flex align-center justify-center" hover="color" theme="danger" @click="deleteClassify(node)">删除</t-link>
                      </t-dropdown-item>
                    </t-dropdown-menu>
                  </template>
                  <icon-font name="edit"></icon-font>
                </t-dropdown>
              </p>
            </template>
          </t-tree>
          <div class="pt24">
            <t-button variant="outline" theme="primary" block @click="handleAddClassify">添加分类</t-button>
          </div>
        </div>
        <div class="lists">
          <div class="filter ">
            <t-space size="12px">
              <t-select style="width: 140px;" v-model="params.status" :options="statusOptions" clearable placeholder="按产品状态" @change="getData">
                <template #label>
                  <icon-font name="layers" style="color: #000;"/>
                </template>
              </t-select>
              <t-input style="width: 220px;" v-model="params.key" clearable placeholder="搜索产品" @change="getData">
                <template #label>
                  <icon-font name="search" size="16px" style="color:#000;font-weight: bold"/>
                </template>
              </t-input>
            </t-space>
          </div>
          <div class="pt16">
            <t-table
              rowKey="id"
              :data="lists"
              :columns="columns"
              :stripe="stripe"
              :bordered="bordered"
              :hover="hover"
              :size="size"
              :max-height="maxHeight"
              :table-layout="tableLayout ? 'auto' : 'fixed'"
              :showHeader="showHeader"
              cellEmptyContent="-"
              resizable
              :loading="loading"
              @page-change="pageChange"
              :pagination="pagination"
              :selected-row-keys="selectedRowKeys"
              @select-change="handleSelectChange"
            >
              <template #icon="{row}">
                <t-image-viewer v-if="row.icon" :images="[row.icon]" :closeOnEscKeydown="false">
                  <template #trigger="{ open }">
                    <div class="tdesign-demo-image-viewer__ui-image" @click="open">
                      <p class="prod-img">
                        <img alt="图片" :src="row.icon" />
                      </p>
                      <div class="tdesign-demo-image-viewer__ui-image--hover">
                        <span><browse-icon size="1.4em"/> </span>
                      </div>
                    </div>
                  </template>
                </t-image-viewer>
                <p v-else>-</p>
              </template>
              <template #selling_price="{row}">
                <p>￥{{ row.selling_price }}</p>
              </template>
              <template #status="{row}">
                <t-tag v-if="row.status === 1" theme="success" shape="round" variant="light">上架</t-tag>
                <t-tag v-if="row.status === 0" theme="warning" shape="round" variant="light">待上架</t-tag>
                <!--<t-tag v-if="row.status === -1" theme="danger" shape="round" variant="light">作废</t-tag>-->
              </template>
              <template #option="{row}">
                <t-space size="12px">
                  <t-link theme="primary" class="edit-btn-color" variant="outline" hover="color" @click="handleEdit(row)">编辑</t-link>
                  <!--<t-link theme="warning" class="opt-btn" variant="outline" hover="color" @click="handleCopy(row)">复制</t-link>-->
                  <t-popconfirm theme="danger" placement="top-right" confirm-btn="删除"
                                @confirm="handleDelete($event, row)">
                    <template #content>
                      <div>
                        <h3 class="popconfirm-title">确认删除？</h3>
                        <p>删除后数据将不可恢复！是否确认删除？</p>
                      </div>
                    </template>
                    <t-link theme="danger" variant="outline" hover="color">删除</t-link>
                  </t-popconfirm>
                </t-space>
              </template>
            </t-table>
          </div>
        </div>
      </div>
    </t-card>

    <!-- 添加分类 -->
    <add-classify ref="classify" @refresh="getClassifyList"></add-classify>
    <!-- 添加产品 -->
    <add-product ref="product" @refresh="getData"></add-product>
  </div>
</template>

<script lang="jsx">
import {IconFont, BrowseIcon} from "tdesign-icons-vue";
import IconUAV from "@/components/icon-UAV/index.vue";
import ProductAdd from "@/pages/product/list/add/index.vue";
import {classifyDeleteApi, classifyListApi} from "@/api/classify";
import {productDeleteApi, productEditApi, productListApi} from "@/api/product";
import AddClassify from "@/pages/product/applet-index/components/add-classify.vue";
import AddProduct from "@/pages/product/applet-index/components/add-product.vue";



export default {
  name: 'AppleIndex',
  components: {AddProduct, AddClassify, IconUAV, IconFont, BrowseIcon, ProductAdd},
  data() {
    return {
      params: {
        page: 1,  // 当前页
        limit: 10,  // 每页条数
        belong_module: 'applet_classify',
        belong_id: '', // 模块id
        pid: '',  // 父级
        key: '',  // 关键字
        status: '', // 状态
      },
      classifyOptions: [],
      brandOptions: [],
      statusOptions: [
        //（-1 作废；0 禁用；1 启用）
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 },
        { label: '作废', value: -1 },
      ], // 状态
      levelOptions: [
        {label: '5级', value: 5},
        {label: '4级', value: 4},
        {label: '3级', value: 3},
        {label: '2级', value: 2},
        {label: '1级', value: 1},
      ],

      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        //{colKey: 'row-select', type: 'multiple', width: 50,},
        {colKey: 'id', title: 'ID', width: 70},
        {colKey: 'icon', title: '产品图', align: 'center', width: 220,},
        {colKey: 'title', title: '产品名称', ellipsis: true},
        //{colKey: 'classify_title', title: '分类', width: 140, ellipsis: true},
        //{colKey: 'brand_title', title: '品牌', width: 140, ellipsis: true},
        //{colKey: 'day_rent', title: '日租价', width: 120},
        //{colKey: 'unit_title', title: '单位', align: 'center', width: 220},
        //{colKey: 'selling_price', title: '售卖价', width: 220},
        //{colKey: 'cash_pledge', title: '租赁押金', width: 140},
        //{colKey: 'stock_num', title: '库存', width: 90},
        {colKey: 'status', title: '状态', width: 220},
        //{colKey: 'sort', title: '排序', width: 100},
        {colKey: 'option', title: '操作', fixed: 'right', width: 140},
      ],
      selectedRowKeys: [],
      pagination: {
        current: 1,
        pageSize: 10,
      },
      maxHeight: 472,
      loading: false,

      items: [],

      mydialog: null
    };
  },
  mounted() {
    this.resetMaxHeight()
    window.onresize = () => {
      this.resetMaxHeight()
    };

    this.getClassifyList()

    this.getData()
  },
  methods: {
    // 添加分类
    handleAddClassify() {
      this.$refs.classify.open('add')
    },
    // 编辑分类
    editClassify(item) {
      this.$refs.classify.open('edit', item.data)
    },
    // 删除分类
    deleteClassify(item) {
      if (this.mydialog) {
        this.mydialog.show();
        return;
      }
      this.mydialog = this.$dialog({
        header: '删除分类',
        theme: 'danger',
        body: `是否确认删除【${item.label}】分类`,
        onConfirm: ({ e }) => {
          this.handleDeleteClassify(item)
        },
      });
    },
    // 确认删除分类
    handleDeleteClassify(item) {
      classifyDeleteApi({id: item.value}).then(res => {
        this.$message.success('删除成功')
        this.getClassifyList()
        this.mydialog.hide();
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 获取分类列表
    getClassifyList() {
      const params = {
        page: 1,
        limit: 9999,
        belong_module: 'applet_classify',
      }
      classifyListApi(params).then(res=> {
        this.classifyOptions = res.data.map(item=> ({label: item.title,value: item.id,}))
        let lists = res.data.map(item=> {
          return {
            label: item.title,
            value: item.id,
            id: item.id,
            pid: item.pid,
          }
        })
        const hierarchy = this.buildHierarchyRecursive(lists)
        const items = [{label: '全部', value: '0', id: '0', pid: '0', expanded:true, children: hierarchy}]
        this.items = items
        //this.items = hierarchy

        const currnt = hierarchy.find(item => item.id === this.params.pid)
        //if (hierarchy.length && !currnt) {
        //  this.params.pid = hierarchy[0].id
        //  this.getData()
        //}
      })
    },
    buildHierarchyRecursive(data, pid = 0) {
      return data
        .filter(item => item.pid === pid)
        .map(item => ({
          ...item,
          //children: this.buildHierarchyRecursive(data, item.id)
        }));
    },
    resetMaxHeight() {
      if (this.selectedRowKeys.length) {
        // 获取屏幕高度 - 顶部高度
        let height = document.documentElement.clientHeight - 300;
        this.maxHeight = height
      } else {
        // 获取屏幕高度 - 顶部高度
        let height = document.documentElement.clientHeight - 250;
        this.maxHeight = height
      }
    },
    // 修改状态
    handleChangeStatus(status) {
      productEditApi({id: this.selectedRowKeys.join(','), status}).then(res => {
        this.$message.success(status ? '上架成功' : '下架成功')
        this.getList()
        this.selectedRowKeys = []
        this.resetMaxHeight()
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 切换分页
    pageChange(pageInfo) {
      const {current,pageSize,} = pageInfo
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.getList()
    },
    // 获取数据
    getData() {
      this.pagination.current = 1
      this.getList()
    },
    // 获取列表
    getList() {
      this.loading = true
      this.params.page = this.pagination.current
      this.params.limit = this.pagination.pageSize
      classifyListApi({...this.params}).then(res => {
        this.pagination.total = res.count
        this.lists = res.data.filter(item=> item.pid !== 0)
      }).catch(err => {
      }).finally(() => {
        this.loading = false
      })
    },
    classifyClick(value) {
      this.params.pid = value.node.value
      this.getData()
    },
    // 添加产品
    goProductAdd() {
      this.$refs.product.open('add');
    },
    // 编辑
    handleEdit(row) {
      this.$refs.product.open('edit', row)
    },
    // 复制
    handleCopy(row) {
      this.$refs.product.open('copy', row)
    },
    handleDelete(event, row) {
      classifyDeleteApi({id: row.id}).then(res => {
        this.$message.success('删除成功')
        this.getList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    handleSelectChange(value, {selectedRowData}) {
      this.selectedRowKeys = value;
      this.resetMaxHeight()
    },
  },
}
</script>

<style lang="less" scoped>
.book-detail {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #FFFFFF;
  border-radius: var(--td-radius-medium);

  .add-btn {
    border-radius: var(--td-radius-medium);
  }

  .content {
    display: flex;
    height: 100%;
    gap: 12px;

    /deep/ .classify {
      width: 247px;
      padding: 18px;
      flex-shrink: 0;
      overflow-x: hidden;
      overflow-y: auto;
      max-height: 100%;
      box-sizing: border-box;
      border: 1px solid #E5E5E5;

      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        border: 0px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
        border-radius: 11px;
      }

      .t-is-active .t-tree__label {
        color: var(--td-brand-color);
      }
    }


    /deep/ .filter {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .t-input, .t-input.t-is-readonly {
        background-color: #F8F8F8;
      }
    }

  }

  /deep/ .card {
    height: 100%;
    display: flex;
    flex-direction: column;

    .t-card__header {
      padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);
      padding-bottom: 0;
    }

    .t-card__body {
      flex: 1;
      height: 100%;
      max-height: calc(100% - 58px);
    }
  }

  .lists {
    position: relative;

    .footer {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 99;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #F9F9F9;
      padding: var(--td-comp-paddingTB-m) var(--td-comp-paddingLR-xl);
      padding-right: var(--td-comp-paddingLR-xxl);
    }
  }
}

</style>
